const mqtt = require('aliyun-iot-mqtt');
// 1. 设备身份信息
var options = {
  productKey: "j0rkzrUrf05",
  deviceName: "sm_01",
  deviceSecret: "1868b070d5364041cff90a1bdcb3d54e",
  host: "iot-06z00frq8umvkx2.mqtt.iothub.aliyuncs.com"
};

// 2. 建立MQTT连接
const client = mqtt.getAliyunIotMqttClient(options);
//订阅云端指令Topic
client.subscribe(`/${options.productKey}/${options.deviceName}/user/get`)
client.subscribe(`/sys/${options.productKey}/${options.deviceName}/thing/event/property/post_reply`)
client.on('message', function (topic, message) {
  console.log("topic " + topic)
  console.log("message " + message)
})

setInterval(function () {
  // 3.定时上报温湿度数据
  client.publish(`/sys/${options.productKey}/${options.deviceName}/thing/event/property/post`, getPostData(), { qos: 0 });
}, 5 * 1000);

function getPostData () {
	

	//呼吸率 取值范围：1 ~ 1000
	var respiratoryRate = Math.floor((Math.random() * 20) + 80);
	//心率   取值范围：1 ~ 1000
	var heartRate = Math.floor((Math.random() * 20) + 20);
	//睡眠状态   
	var shuimianzhuangtai = [0, 1, 2][Math.floor(Math.random() * 3)];
	//离床次数 
	var lichuangcishu = Math.floor((Math.random() * 20) + 3);
	
	//离床时间
	var lichuagnshijian;

	if(shuimianzhuangtai === 2 ){
		lichuagnshijian = new Date();
	}
	
  const payloadJson = {
    id: Date.now(),
    version: "1.0",
    params: {
      RespiratoryRate: respiratoryRate,
      HeartRate: heartRate,
      shuimianzhuangtai: shuimianzhuangtai,
      lichuangcishu: lichuangcishu,
      lichuagnshijian: lichuagnshijian
    },
    method: "thing.event.property.post"

  }
  console.log("payloadJson " + JSON.stringify(payloadJson))
  return JSON.stringify(payloadJson);
}